package com.kokuma.drawsprite.guide.services.impl;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.kokuma.drawsprite.common.DateTimeUtil;
import com.kokuma.drawsprite.common.StaticValue;
import com.kokuma.drawsprite.ftp.util.FTPUtil;
import com.kokuma.drawsprite.guide.dao.IBsUploadFileInfoDao;
import com.kokuma.drawsprite.guide.models.BsFileInfo;
import com.kokuma.drawsprite.guide.models.BsUploadFileInfo;
import com.kokuma.drawsprite.guide.services.interfaces.IBsFileInfoServices;
import com.kokuma.drawsprite.guide.services.interfaces.IBsUploadFileInfoServices;

@Service("IBsUploadFileInfoServices")
public class IBsUploadFileInfoImpl implements IBsUploadFileInfoServices {

	@Resource
	IBsUploadFileInfoDao bsUploadFileInfoDao;
	@Resource
	IBsFileInfoServices bsFileInfoServices;
	

	@Override
	public int addBsUploadFileInfo(BsUploadFileInfo bean) {
		// TODO Auto-generated method stub
		return bsUploadFileInfoDao.addBsUploadFileInfo(bean);
	}

	@Transactional
	public JSONObject upUploadGuideFile(MultipartFile file, String... params) throws Exception {
		String newFileName = UUID.randomUUID().toString();
		String oriName = file.getOriginalFilename();
		String extName = oriName.substring(oriName.lastIndexOf("."));
		File newFile=new File(newFileName+extName);
		file.transferTo(newFile);
		FTPUtil ftpClient = getGuideFtpClient();
		ftpClient.uploadFile(newFile);
		Timestamp now = DateTimeUtil.getCurrentDate();
		BsUploadFileInfo bsUploadFileInfo=new BsUploadFileInfo();
		bsUploadFileInfo.setOpDate(now);
		bsUploadFileInfo.setBusiType(StaticValue.BUSI_TYPE_GUIDE);
		
		
		BsFileInfo bsFileInfo=new BsFileInfo();
		bsFileInfo.setBusiId(bsUploadFileInfo.getBusiId());
		bsFileInfo.setBusiType(StaticValue.BUSI_TYPE_GUIDE);
		bsFileInfo.setCrtTime(now);
		bsFileInfo.setFileName(newFileName);
		bsFileInfo.setFileSize(file.getSize());
		bsFileInfo.setFileSuffix(extName);
		bsFileInfo.setFullPath(ftpClient.getRemotePath()+"/"+newFileName+extName);
		bsFileInfo.setOpType(StaticValue.FILE_OP_TYPE_UPLOAD);
		bsFileInfo.setOriFileName(oriName);
		bsFileInfo.setPathCode(ftpClient.getCfgPathCode());
		
		bsUploadFileInfo.setUrl(ftpClient.getProxyUrl()+"/"+bsFileInfo.getFullPath());
		int count=this.addBsUploadFileInfo(bsUploadFileInfo);
		bsFileInfoServices.addBsFileInfoUploadInfo(bsFileInfo);
		
		JSONObject ret=new JSONObject();
		
		ret.put("busiId", bsFileInfo.getBusiId());
		ret.put("url", bsUploadFileInfo.getUrl());
		return ret;
	}

	public FTPUtil getGuideFtpClient() {
		FTPUtil ftpClient = new FTPUtil(StaticValue.CFG_FTP_CODE_GUIDE);
		return ftpClient;
	}
}
